package com.bawei.module_home.ui

import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Color
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.view.View
import android.widget.CompoundButton
import androidx.fragment.app.Fragment
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bawei.library_common.route.ARouterActivityPath
import com.bawei.library_mvi.ui.BaseMviActivity
import com.bawei.library_widget.MyGSYVideoPlayer
import com.bawei.library_widget.event.RedPacketEnum
import com.bawei.library_widget.event.RedPacketEvent
import com.bawei.module_home.R
import com.bawei.module_home.databinding.HomeActivityHomeDetailBinding
import com.bawei.module_home.model.entity.SimpleVideoEntity
import com.bawei.module_home.widget.BitmapUtils
import com.bawei.module_home.widget.MyCacheStuffer
import com.google.android.material.tabs.TabLayout
import com.ivideo.home.widget.DanMuBottomSheetDialog
import com.shuyu.gsyvideoplayer.GSYVideoManager
import com.shuyu.gsyvideoplayer.listener.GSYSampleCallBack
import master.flame.danmaku.controller.DrawHandler
import master.flame.danmaku.danmaku.model.BaseDanmaku
import master.flame.danmaku.danmaku.model.Danmaku
import master.flame.danmaku.danmaku.model.DanmakuTimer
import master.flame.danmaku.danmaku.model.IDanmakus
import master.flame.danmaku.danmaku.model.android.BaseCacheStuffer
import master.flame.danmaku.danmaku.model.android.DanmakuContext
import master.flame.danmaku.danmaku.model.android.Danmakus
import master.flame.danmaku.danmaku.parser.BaseDanmakuParser
import org.greenrobot.eventbus.EventBus
import java.util.*
import kotlin.collections.HashMap

@Route(path = ARouterActivityPath.HOMEDETAIL)
class HomeDetailActivity : BaseMviActivity<HomeActivityHomeDetailBinding>(){
    @Autowired
    lateinit var videoData:SimpleVideoEntity
    /**
     * 简介Fragment
     */
    private lateinit var descriptionFragment: HomeDetailDescriptionFragment

    /**
     * 评论Fragment
     */
    private lateinit var commentFragment: HomeDetailCommentFragment

    /**
     * 弹幕库上下文
     */
    private lateinit var dmContext:DanmakuContext
    /**
     * 弹幕解析
     */
    private var danmakuParser =  object :BaseDanmakuParser(){
        override fun parse(): IDanmakus {
            return Danmakus()
        }

    }
    /**
     * 弹幕缓冲
     */
    private val mBackgroundCacheStuffer: BaseCacheStuffer.Proxy =
        object : BaseCacheStuffer.Proxy() {
            override fun prepareDrawing(danmaku: BaseDanmaku, fromWorkerThread: Boolean) {
                // 根据你的条件检查是否需要需要更新弹幕
            }

            override fun releaseResource(danmaku: BaseDanmaku) {
                //清理相应的数据
                danmaku.tag = null
            }
        }

    /**
     * 弹幕颜色 随机
     */
    private val mContentColorBg = arrayOf("#0099ff", "#b2d15c", "#b9b9f1", "#f46c77")

    /**
     * 模拟弹幕发送
     */
    private val mHandler: Handler = Handler()

    override fun handleState() {

    }

    override fun initEnv() {
        super.initEnv()
        ARouter.getInstance().inject(this)
    }

    override fun initView() {
        super.initView()
        initFragment()
        initGsy()
        initDanMu()
    }



    override fun initEvent() {
        super.initEvent()
        //模拟虚假弹幕
        mHandler.postDelayed(object :Runnable{
            override fun run() {
                addDanmaku(false,"46646464")
                mHandler.postDelayed(this,1000)
            }
        },1000)
        //点击tab切换
        viewDataBinding.tabHomeDetailType.addOnTabSelectedListener(object: TabLayout.OnTabSelectedListener{
            override fun onTabSelected(tab: TabLayout.Tab?) {
                if (tab?.text==getString(R.string.home_detail_descriptioin)){
                    //评论切换到简介
                    switchFragment(R.id.fl_home_detail_content,commentFragment,descriptionFragment)
                }
                else{
                    //简介切换到评论
                    switchFragment(R.id.fl_home_detail_content,descriptionFragment,commentFragment)
                }
//
            }

            override fun onTabUnselected(tab: TabLayout.Tab?) {
            }

            override fun onTabReselected(tab: TabLayout.Tab?) {
            }

        })

        //点击
        viewDataBinding.ivHomeDetailBack.setOnClickListener {
            finish()
        }
        viewDataBinding.ivHomeDetailSearch.setOnClickListener {

        }
        viewDataBinding.ivHomeDetailTv.setOnClickListener {

        }
        viewDataBinding.ivHomeDetailMore.setOnClickListener {

        }
        //弹幕开关
        viewDataBinding.switchHomeDetailBulletscreen.setOnCheckedChangeListener { buttonView, isChecked ->
            if (isChecked) {
                //设置解析器
                val defaultDanmakuParser = danmakuParser
                viewDataBinding.dvHomeDetail.prepare(defaultDanmakuParser, dmContext)
                viewDataBinding.dvHomeDetail.resume()
            } else {
                viewDataBinding.dvHomeDetail.stop()
            }
        }
        /**
         * 发送弹幕
         */
        viewDataBinding.tvHomeDetailDanmu.setOnClickListener {
            //结合fragment和dialog
            val bottom= DanMuBottomSheetDialog()
            bottom.setDanMuListener(object : DanMuBottomSheetDialog.DanMuListener{
                override fun onClick() {
                    val content = bottom.etContent?.text.toString()
                    if (content.isBlank()){
                        showMsg("请输入弹幕内容")
                        return
                    }
                    addDanmaku(false,content)
                    bottom.close()//关闭
                }
            })
            bottom.show(supportFragmentManager,"DanMuBottomSheetDialog")
        }


    }


    override fun getLayout(): Int {
       return R.layout.home_activity_home_detail
    }

    override fun generateViewModel() {

    }
    //红包开始滚动
    override fun onWindowFocusChanged(hasFocus: Boolean) {
        super.onWindowFocusChanged(hasFocus)
        //开始执行红包动画
        EventBus.getDefault().post(RedPacketEvent(RedPacketEnum.INIT))
    }
    //红包释放资源
    override fun onStop() {
        super.onStop()
        viewDataBinding.rpvHomeDetailRedpacket.releaseRes()
    }


    /**
     * 初始化弹幕
     */
    private fun initDanMu() {
        //设置最大显示行数
        val maxLInesPair: HashMap<Int, Int> = HashMap(16)
        maxLInesPair[BaseDanmaku.TYPE_SCROLL_RL] = 8 //从右向左滚动
        //设置是否禁止重叠
        val overlappingEnablePair: HashMap<Int, Boolean> = HashMap(16)
        overlappingEnablePair[BaseDanmaku.TYPE_SCROLL_RL] = true
        overlappingEnablePair[BaseDanmaku.TYPE_FIX_TOP] = true
        //创建弹幕上下文
        dmContext = DanmakuContext.create()
        //设置一些相关的配置
        dmContext.setDuplicateMergingEnabled(false) //是否重复合并
            .setScrollSpeedFactor(1.2f) //设置文字的比例
            .setScaleTextSize(1.2f) //图文混排的时候使用！这里可以不用
            .setCacheStuffer(MyCacheStuffer(this), mBackgroundCacheStuffer) //设置绘制弹幕的样式
            .setMaximumLines(maxLInesPair) //设置防，null代表可以重叠
            .preventOverlapping(overlappingEnablePair)


        if (viewDataBinding.dvHomeDetail != null) {

            //相应的回掉
            viewDataBinding.dvHomeDetail.setCallback(object : DrawHandler.Callback {
                override fun updateTimer(timer: DanmakuTimer) {
                    //定时器更新的时候回掉
                }

                override fun drawingFinished() {
                    //弹幕绘制完成时回掉
                }

                override fun danmakuShown(danmaku: BaseDanmaku) {
                    //弹幕展示的时候回掉
                }

                override fun prepared() {
                    //弹幕准备好的时候回掉，这里启动弹幕
                    viewDataBinding.dvHomeDetail.start()
                }
            })
            viewDataBinding.dvHomeDetail.prepare(danmakuParser, dmContext)
            viewDataBinding.dvHomeDetail.enableDanmakuDrawingCache(true)
        }
    }
    //初始化视频
    private fun initGsy() {
        //设置视频资源
        viewDataBinding.gsyHomeDetail.setUp(videoData?.videopath,true,"")
//        viewDataBinding.gsyHomeDetail.setUpLazy(videoData?.videopath,true,null,null,"")
        viewDataBinding.gsyHomeDetail.titleTextView.visibility= View.GONE
        viewDataBinding.gsyHomeDetail.backButton.visibility=View.GONE
        viewDataBinding.gsyHomeDetail.fullscreenButton.setOnClickListener {
            viewDataBinding.gsyHomeDetail.startWindowFullscreen(this@HomeDetailActivity,false,true)
        }
        viewDataBinding.gsyHomeDetail.isShowFullAnimation=true
        //播放视频
        viewDataBinding.gsyHomeDetail.startPlayLogic()


        /**
         * 视频点击暂停 恢复处理
         */
        viewDataBinding.gsyHomeDetail.setVideoAllCallBack(object : GSYSampleCallBack() {
            override fun onClickResume(url: String?, vararg objects: Any?) {
                super.onClickResume(url, *objects)
                EventBus.getDefault().post(RedPacketEvent(RedPacketEnum.RESUME))
                dmResume()//弹幕恢复
            }

            override fun onClickStop(url: String?, vararg objects: Any?) {
                super.onClickStop(url, *objects)
                EventBus.getDefault().post(RedPacketEvent(RedPacketEnum.PAUSE))
                dmPause()//弹幕暂停
            }


        })

        /**
         * 视频播放完处理红包执行停止
         */
        viewDataBinding.gsyHomeDetail.setListener(object: MyGSYVideoPlayer.MyGSYVideoPlayerStateListener{
            override fun finish() {
                EventBus.getDefault().post(RedPacketEvent(RedPacketEnum.PAUSE))
                //视频播放完成关闭并释放弹幕
                releaseDM()
            }

            override fun start() {
            }

        })

    }
    //加载简介和评论
    private fun initFragment() {
        //设置tab内容
        viewDataBinding.tabHomeDetailType.addTab(viewDataBinding.tabHomeDetailType.newTab().setText(getString(R.string.home_detail_descriptioin)))
        viewDataBinding.tabHomeDetailType.addTab(viewDataBinding.tabHomeDetailType.newTab().setText(getString(R.string.home_detail_recomment)))

        val bundle = Bundle()
        bundle.putParcelable("data",videoData)
        //创建Fragment并传递参数
        descriptionFragment= HomeDetailDescriptionFragment()
        descriptionFragment.arguments=bundle
        commentFragment= HomeDetailCommentFragment()
        commentFragment.arguments=bundle
        //添加fragment
        supportFragmentManager.beginTransaction().add(R.id.fl_home_detail_content,descriptionFragment).commitAllowingStateLoss()
    }

    /**
     * 装填弹幕并发送
     */
    private fun addDanmaku(islive: Boolean,content:String) {
        //创建一条弹幕
        val danmaku: BaseDanmaku =
            dmContext.mDanmakuFactory.createDanmaku(BaseDanmaku.TYPE_SCROLL_RL)

        if (danmaku == null || viewDataBinding.dvHomeDetail == null) {
            return
        }

        //设置相应的数据

        var showBitmap: Bitmap = BitmapFactory.decodeResource(resources, com.bawei.library_widget.R.drawable.home_danmu)
        showBitmap = BitmapUtils.getShowPicture(showBitmap)
        val map: MutableMap<String, Any> = HashMap(16)
        map["content"] = content
        map["bitmap"] = showBitmap
        val random = Random()
        val randomNum: Int = random.nextInt(mContentColorBg.size)
        map["color"] = mContentColorBg.get(randomNum)
        //设置相应的tag
        danmaku.tag = map
        danmaku.textSize = 0f
        danmaku.padding = 10
        danmaku.text = ""
        // 一定会显示, 一般用于本机发送的弹幕
        danmaku.priority = 1
        danmaku.isLive = false
        danmaku.time = viewDataBinding.dvHomeDetail.getCurrentTime()
        danmaku.textColor = Color.WHITE
        // 重要：如果有图文混排，最好不要设置描边(设textShadowColor=0)，否则会进行两次复杂的绘制导致运行效率降低
        danmaku.textShadowColor = 0
        //添加一条
        viewDataBinding.dvHomeDetail.addDanmaku(danmaku)
    }
    /**
     * 弹幕暂停
     */
    private fun dmPause(){
        if (viewDataBinding.dvHomeDetail != null && viewDataBinding.dvHomeDetail.isPrepared()) {
            viewDataBinding.dvHomeDetail.pause();
        }
    }

    /**
     * 弹幕恢复
     */
    private fun dmResume(){
        if (viewDataBinding.dvHomeDetail != null && viewDataBinding.dvHomeDetail.isPrepared() && viewDataBinding.dvHomeDetail.isPaused()) {
            viewDataBinding.dvHomeDetail.resume();
        }
    }

    /**
     * 释放弹幕
     */
    private fun releaseDM(){
        if (viewDataBinding.dvHomeDetail != null) {
            // dont forget release!
            viewDataBinding.dvHomeDetail.release();

        }
    }

    override fun onPause() {
        super.onPause()
        viewDataBinding.gsyHomeDetail.onVideoPause()
        dmPause()
    }

    override fun onResume() {
        super.onResume()

        viewDataBinding.gsyHomeDetail.onVideoResume()
        dmResume()
    }

    override fun onDestroy() {
        super.onDestroy()
        GSYVideoManager.releaseAllVideos()
        releaseDM()
//        overridePendingTransition(0,R.anim.anim_in);
    }

    override fun onBackPressed() {
        super.onBackPressed()
        releaseDM()
    }

    //切换fragment from：从哪个fragment切换到to：fragment
    fun switchFragment(fl:Int,from: Fragment?, to: Fragment) {
        if (!to.isAdded()) {//是否添加到此容器中
            supportFragmentManager.beginTransaction().hide(from!!).add(fl, to).commit()
        } else {
            supportFragmentManager.beginTransaction().hide(from!!).show(to).commit()
        }
    }

}